package Flap::Logger;
use Flap qw/-b Flap::Object -m -s -w/;
use IO::Handle;

sub new {
    my $class = shift;
    my $proj = $class->project;
    my $self = bless {
        dir    => $proj->config->log_dir,
        suffix => $proj->hostname.(@_ ? "_$_[0]" : ''),
        ymd    => '',
    }, $class;
    $self->now;
    $self;
}

sub now {
    my $self = shift;
    my $now = $self->project->now;
    if($now->ymd ne $self->{ymd}){
        $self->{H}->close if $self->{H};
        $self->{ymd} = $now->ymd;
        my $path = $self->path;
        if(!-f $path){
            (my $dir = $path) =~ s%/[^/]+\z%% || die $path;
            $self->OS->mkdir_p($dir) if !-d $dir;
        }
        $self->OS->open($self->{H}, '>>', $path) || die "$!($path)";
        $self->{H}->autoflush;
    }
    $now;
}

sub path { "$_[0]->{dir}/$_[0]->{ymd}_$_[0]->{suffix}.log" }

sub print { shift->{H}->print(@_) }

sub write {
    my $self = shift;
    my $now = $self->now;
    $self->print($self->Util->ary2tsv($now->hms, @_)."\n");
}

1;
